import { defineStore } from 'pinia'
import { ref } from 'vue'
import request from '../utils/request'
import { message } from 'ant-design-vue'

export const useDatabaseStore = defineStore('database', () => {
  // 状态
  const connections = ref([])
  const loading = ref(false)
  const currentConnection = ref(null)
  const testResult = ref(null)
  const databases = ref([])

  // 动作
  const fetchConnections = async (params = {}) => {
    loading.value = true
    try {
      const response = await request.post('/v1/connections/getConnectionList', {
        ...params
      })
      // 确保返回的数据格式正确
      const list = response.data?.list || []
      const total = response.data?.total || 0
      
      // 处理数据，确保每个记录都有必要的字段
      const processedList = list.map(item => ({
        id: item.id,
        name: item.name || '',
        type: item.type || '',
        host: item.host || '',
        port: item.port || '',
        database: item.database || '',
        username: item.username || '',
        status: item.status || 'disconnected',
        created_at: item.created_at,
        updated_at: item.updated_at
      }))

      return {
        data: processedList,
        total: total
      }
    } catch (error) {
      // 如果是 404 错误，返回空列表
      if (error.response?.status === 404) {
        return {
          data: [],
          total: 0
        }
      }
      throw error
    } finally {
      loading.value = false
    }
  }

  const createConnection = async (data) => {
    try {
      const response = await request.post('/v1/connections/createConnection', data)
      return response.data
    } catch (error) {
      if (error.response?.status === 503) {
        throw new Error('无法连接到数据库服务器，请确保服务器正在运行且可访问')
      } else if (error.response?.status === 409) {
        throw new Error('连接名称已存在，请使用其他名称')
      } else if (error.response?.status === 400) {
        throw new Error(error.response.data.error || '请填写所有必填字段')
      }
      throw new Error(error.response?.data?.error || '创建数据库连接失败')
    }
  }

  const updateConnection = async (id, data) => {
    try {
      const response = await request.put(`/v1/connections/${id}`, data)
      return response.data
    } catch (error) {
      throw new Error(error.response?.data?.error || '更新数据库连接失败')
    }
  }

  const deleteConnection = async (id) => {
    try {
      await request.delete(`/v1/connections/${id}`)
    } catch (error) {
      throw new Error(error.response?.data?.error || '删除数据库连接失败')
    }
  }

  const testConnection = async (id) => {
    try {
      const response = await request.post('/connections/test')
      return response.data
    } catch (error) {
      throw new Error(error.response?.data?.error || '测试数据库连接失败')
    }
  }

  const getConnection = async (id) => {
    try {
      const response = await request.post(`/connections/${id}`)
      currentConnection.value = response.data
      return response.data
    } catch (error) {
      throw new Error(error.response?.data?.error || '获取数据库连接失败')
    }
  }

  const fetchDatabases = async (params = {}) => {
    loading.value = true
    try {
      const response = await request.get('/databases', { params })
      return response.data
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  const createDatabase = async (data) => {
    try {
      const response = await request.post('/databases', data)
      return response.data
    } catch (error) {
      throw error
    }
  }

  const updateDatabase = async (id, data) => {
    try {
      const response = await request.put(`/databases/${id}`, data)
      return response.data
    } catch (error) {
      throw error
    }
  }

  const deleteDatabase = async (id) => {
    try {
      await request.delete(`/databases/${id}`)
    } catch (error) {
      throw error
    }
  }

  const testConnectionDatabase = async (connection) => {
    try {
      const startTime = Date.now()
      const response = await request.post('/v1/connections/test', connection)
      const endTime = Date.now()
      
      return {
        success: true,
        time: endTime - startTime,
        data: response.data
      }
    } catch (error) {
      throw new Error(error.response?.data?.message || '测试连接失败')
    }
  }

  const fetchStatistics = async () => {
    try {
      const response = await request.get('/databases/statistics')
      return response.data
    } catch (error) {
      throw error
    }
  }

  return {
    connections,
    loading,
    currentConnection,
    testResult,
    fetchConnections,
    createConnection,
    updateConnection,
    deleteConnection,
    testConnection,
    getConnection,
    databases,
    fetchDatabases,
    createDatabase,
    updateDatabase,
    deleteDatabase,
    testConnectionDatabase,
    fetchStatistics
  }
})